﻿using System;
using System.Web;
using System.Windows;
using QQWeiBoSDK;
using MessageBox = System.Windows.MessageBox;

namespace Pages
{
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class Settings
    {
        private readonly OAuthBase _oAuth;// = new oAuthQQ();

        public Settings(OAuthBase oauth) {
            InitializeComponent();

            _oAuth = oauth;
            // Clean up token and tokensecret
            _oAuth.Token = string.Empty;
            _oAuth.TokenSecret = string.Empty;
            Title = @"登录" + _oAuth.Title;

            //Get the authorization url.
            Uri url = new Uri(_oAuth.AuthorizationLinkGet());

            //Save the token.
            _oAuth.Token = HttpUtility.ParseQueryString(url.Query)["oauth_token"];

            //Show the intro text with the authorization link.
            string html = @"<html><head><meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" />"
                +"<title></title><style type='text/css'>body {background-color:#5599BB;color:#ffffff;font-family:arial;}img{border:none}</style></head><body>"
                + "<h1>" + _oAuth.Title + "认证</h1><p>请登录.</p>"
                + "<p></p>"
                + "<p>登录之后，会显示一个PIN码</p>"
                + "<p>请在下方输入PIN码，点击确定继续</p>"
                + "<p><a href=\"" + url + "\"><img src=\""+ _oAuth.LinkIconUrl + "\" alt=\"使用微博登录\" /></a></p>"
                + "</body></html>";

            WebBrowser.NavigateToString(html);
        }

        private void BtnOkClick(object sender, RoutedEventArgs e) {
            try {
                _oAuth.Verifier = txtUpdate.Text.Trim();
                _oAuth.AccessTokenGet(_oAuth.Token, _oAuth.Verifier);
                _oAuth.SaveTokenAndTokenSecret();
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void BtnCancelClick(object sender, RoutedEventArgs e) {
            Close();
        }
    }
}
